from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from . import serializers
from rest_framework.generics import CreateAPIView, RetrieveAPIView

from .models import User


class UserView(CreateAPIView):
    """
    用户注册
    """
    serializer_class = serializers.CreateUserSerializer

class UsernameCountView(APIView):
    """判断用户名是否存在"""

    def get(self, request, username):
        # 使用username作为条件查询满足条件的记录的数量
        count = User.objects.filter(username=username).count()

        # 构造响应数据
        data = {
            'username': username,
            'count': count
        }

        # 响应数据
        return Response(data)
class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = serializers.UserDetailSerializer  # 指定序列化器类
    permission_classes = [IsAuthenticated]  # 设置访问权限

    def get_object(self):
        # 重写此方法返回当前的登录用户
        return self.request.user